'use strict';

const Service = require('egg').Service;

class UserService extends Service {
	async searchAll() {
		// 假如 我们拿到用户 id 从数据库获取用户详细信息
		const users = await this.app.mysql.select('user');
		return {
			users
		};
	}

	async find(phone) {
		const user = await this.app.mysql.get('user', {
			phone
		});
		return user;
	}
	
	convertToTree(regions, rootId = "0") {
		return regions.filter(item => item.pid == rootId).map(item => (item.children = this.convertToTree(regions,
			item.id), item))
	}

	async findrole(ids) {
		const roleids = ids.split(',');
		const rolelist = await this.app.mysql.select('dts_role', {
			where: {
				id: roleids,
			},
			columns: ['name']
		});
		var wherepar = {
			role_id: roleids,
		};
		
		const menuids = await this.app.mysql.select('dts_role_menu', {
			where: wherepar,
			columns: ['menuids']
		});
		var menuid = menuids[0].menuids.split(',');
		const menu = await this.app.mysql.select('dts_menu', {
			where: {
				id: menuid
			},
		});
		var menulist = this.convertToTree(menu, 0);
		const rolename = rolelist.map(item => item.name);
		const buttonids = await this.app.mysql.select('dts_role_permission', {
			where: wherepar,
			columns: ['buttonids']
		});
		var buttonlist = [];
		buttonids.forEach(item=>{
			if(item.buttonids){
				var arr = item.buttonids.split(',');
				buttonlist.push(...arr);
			}
		});
		var autro = buttonlist.length>0?Array.from(new Set(buttonlist)):[];
		var autrotext = [];
		if(autro.length>0){
			autrotext = await this.app.mysql.query(`SELECT buttonbox.id, buttonbox.menu_id, buttonbox.name, buttonbox.identification, menu.id AS menuId, menu.url AS menuurl FROM dts_button AS buttonbox LEFT OUTER JOIN dts_menu AS menu ON buttonbox.menu_id = menu.id WHERE buttonbox.id IN (${autro})`);
			// var Buttonbox = this.ctx.model.Buttonbox;
			// var Menu = this.ctx.model.Menu;
			// Buttonbox.belongsTo(Menu, {
			// 	foreignKey: 'menu_id'
			// })
			
			// autrotext = await Buttonbox.findAll({
			// 	attributes: [ 'menu_id', 'name','identification'],
			// 	include: [{
			// 		model: Menu,
			// 		attributes: ['url'],
			// 	}],
			// 	where: {
			// 		id: autro
			// 	},
			// })
			
			
		}
		return {
			perms: autrotext,
			roles: rolename,
			menu: menulist
		};
	}

	async adduser(data) {
		const user = await this.app.mysql.insert('user', data);
		return {
			user
		};
	}
}

module.exports = UserService;